#!/bin/env python3
#coding=utf-8
from pymongo import MongoClient
from bson.objectid import ObjectId
from random import randint
import time


class Session:
    def __init__(self, actid, token = None):
        self.client = MongoClient("mongodb://127.0.0.1:27017/'")["flare" + str(actid)]
        self.form = self.client.session
        self.gctime = 3600
        self.gcprob = 1
        if token is None:
            self.token = str(self.form.insert({
                "date": time.time()
            }))
        else:
            self.token = token

    def save(self, json):
        if randint(1, self.gcprob) == 1:
            self.gc()

        json['date'] = time.time()
        swap = self.form.find_one({
            "_id": ObjectId(self.token)
        }).update(json)

        self.form.update({
            "_id": ObjectId(self.token)
        }, json)

    def delete(self, key):
        self.form.update({
            "_id": ObjectId(self.token)
        }, {
            "$unset": {"key":key}
        })

    def clear(self):
        self.form.remove({
            "_id": ObjectId(self.token)
        })

    def gets(self, key):
        return self.form.find_one({
            "_id": ObjectId(self.token)
        }).get(key, None)

    def gc(self):
        for once in self.form.find():
            if once["date"] + self.gctime <= time.time():
                self.form.remove({"_id":once["_id"]})

